Python JSON
๐ง How to Read JSON in Python Without Losing Your Sanity (or Your Data)โ
Welcome to the world of json.load()
โ your best pal when it comes to unboxing JSON files into shiny Python objects! Whether youโre building apps, scraping data, or just trying to figure out what that mysterious data.json
file actually holdsโฆ this guide is for YOU.
Buckle up. It's about to get deserializational ๐
๐ TL;DR โ Show Me the Codeโ
If youโre the kind of person who opens gifts before reading the card, hereโs your quick-start gift:
import json
with open('file_dir_location/data.json') as fp:
data = json.load(fp)
# The data is of type 'dict'
print(data)
๐ Boom! You just read a JSON file and converted it into a Python object like a pro. ๐ฉโจ
๐งฌ 1. What on Earth is json.load()
?โ
Glad you asked! json.load()
is like your bilingual buddy who reads JSON and translates it into Python.
๐ Translation Guide: JSON to Pythonโ
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
Basically, json.load()
turns this:
{"name": "AI Bot", "age": 3, "isSmart": true}
Into this:
{'name': 'AI Bot', 'age': 3, 'isSmart': True}
Itโs like magicโฆ but better, because itโs Pythonic.
๐งช 2. Reading JSON Files โ Letโs Get Our Hands Dirtyโ
๐งพ Example 1: Reading a JSON File from the Filesystemโ
Suppose you have a file named users.json
that looks like this:
[
{
"id": 1,
"name": "Sujit",
"username": "Sujit",
"email": "Sujit@gmail.com"
},
{
"id": 2,
"name": "Brian",
"username": "brian",
"email": "brian@gmail.com"
}
]
Your Python script can read it like this:
import json
with open('users.json') as fp:
data = json.load(fp)
# list
print(type(data))
# Verify read data
print(data)
๐จ๏ธ Program output:
<class 'list'>
[{'id': 1, 'name': 'Sujit', 'username': 'Sujit', 'email': 'Sujit@gmail.com'},
{'id': 2, 'name': 'Brian', 'username': 'brian', 'email': 'brian@gmail.com'}]
๐ Note: The root of the JSON is an array, so Python loads it as a list of dictionaries. Itโs like a digital address book, but without the annoying paper cuts.
๐ Example 2: Reading a JSON File from the Interwebsโ
Because sometimes your data lives far, far away (in the Cloud โ๏ธ).
We'll use the trusty requests
library โ think of it as your HTTP butler.
import json
import requests
response = requests.get("https://jsonplaceholder.typicode.com/users")
users = json.loads(response.text)
print(users)
๐ Program output: We wonโt spoil the surprise here. Run the program to see a list of 10 beautiful JSON objectsโeach representing a fake user.
But hereโs a sneak peek:
[{'id': 1, 'name': 'Leanne Graham', 'username': 'Bret', 'email': 'Sincere@april.biz'}, ... ]
Yes, itโs fake data, but hey, it works great for testing and learning!
๐ Conclusion: Go Forth and Deserializeโ
Now you know how to:
- Read JSON from a file like a code wizard ๐ง
- Talk to web servers and grab JSON from URLs ๐ก
- Transform raw JSON into structured Python data ๐
So next time someone says "can you parse this JSON?", you can smile smugly and say:
โAbsolutely. Would you like that loaded or pretty-printed?โ
Happy Learning & Stay JSON-tastic! ๐พโจ